<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";

const formRef = ref(null);
const form = ref({
  name: "",
  gender: "",
  birthDate: "",
  phone: "",
  email: "",
  departmentId: null,
  position: "",
  password: "",
  confirmPassword: "",
  idCard: "",
  status: 1,
});

const photoFile = ref(null);
const photoUrl = ref("");

const departmentList = ref([]);

async function fetchDepartments() {
  try {
    const res = await axios.get("http://127.0.0.1:8080/admin/department/getAll", {
      headers: {
        token: localStorage.getItem("token"),
      },
    });
    const data = res.data;
    if (data.code === 200) {
      departmentList.value = data.data || [];
    } else {
      ElMessage.error(data.message || "获取部门失败");
    }
  } catch (e) {
    ElMessage.error("获取部门失败");
  }
}

onMounted(() => {
  fetchDepartments();
});

const rules = {
  name: [{ required: true, message: "员工姓名不能为空", trigger: "blur" }],
  gender: [{ required: true, message: "员工性别不能为空", trigger: "change" }],
  birthDate: [{ required: true, message: "出生日期不能为空", trigger: "change" }],
  phone: [
    { required: true, message: "联系方式不能为空", trigger: "blur" },
    { pattern: /^\+?[0-9]{7,15}$/, message: "电话号码格式不正确", trigger: "blur" },
  ],
  email: [
    { required: true, message: "邮箱不能为空", trigger: "blur" },
    { type: "email", message: "邮箱格式不正确", trigger: "blur" },
  ],
  departmentId: [{ required: true, message: "所属部门不能为空", trigger: "change" }],
  position: [{ required: true, message: "岗位名称不能为空", trigger: "blur" }],
  password: [{ required: true, message: "员工密码不能为空", trigger: "blur" }],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== form.value.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  status: [{ required: true, message: "员工状态不能为空", trigger: "change" }],
  idCard: [
    { required: true, message: "身份证号码不能为空", trigger: "blur" },
    {
      pattern: /^[1-9]\d{5}\d{4}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
      message: "身份证号码格式不正确",
      trigger: "blur",
    },
  ],
};

function handlePhotoChange(file) {
  console.log('文件信息:', file);
  photoFile.value = file.raw;
  const reader = new FileReader();
  reader.onload = (e) => {
    photoUrl.value = e.target.result;
  };
  reader.readAsDataURL(file.raw);
}

function handlePhotoRemove() {
  photoFile.value = null;
  photoUrl.value = "";
}

async function onSubmit() {
  try {
    const valid = await formRef.value.validate();
    if (valid) {
      const formData = new FormData();
      const jsonData = {};
      Object.keys(form.value).forEach((key) => {
        if (
          form.value[key] !== null &&
          form.value[key] !== "" &&
          key !== "confirmPassword"
        ) {
          jsonData[key] = form.value[key];
        }
      });
      formData.append("jsonData", JSON.stringify(jsonData));
      
      // 添加调试信息
      console.log('photoFile.value:', photoFile.value);
      if (photoFile.value) {
        formData.append("photo", photoFile.value);
        console.log('已添加照片到FormData');
      } else {
        console.log('没有照片文件');
      }
      
      // 打印FormData内容用于调试
      for (let [key, value] of formData.entries()) {
        console.log('FormData内容:', key, value);
      }
      
      const response = await axios.post(
        "http://127.0.0.1:8080/admin/emp/empAdd",
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
            token: localStorage.getItem("token"), // 如果需要token验证
          },
        }
      );
      const result = response.data;
      if (result.code === 200) {
        alert("员工添加成功！");
        onReset();
      } else {
        ElMessage.error(result.message || "添加失败");
      }
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("提交失败，请检查网络连接");
  }
}

function onReset() {
  formRef.value.resetFields();
  photoFile.value = null;
  photoUrl.value = "";
}
</script>

<template>
  <el-card class="add-emp-card" shadow="hover">
    <h2>添加员工</h2>
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
      <el-form-item label="员工姓名" prop="name">
        <el-input v-model="form.name" placeholder="请输入员工姓名" />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="form.gender">
          <el-radio label="男">男</el-radio>
          <el-radio label="女">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="出生日期" prop="birthDate">
        <el-date-picker
          v-model="form.birthDate"
          type="date"
          placeholder="选择日期"
          value-format="YYYY-MM-DD"
          teleported
        />
        <span class="date-format-note">格式：<i>YYYY-MM-DD</i></span>
      </el-form-item>

      <el-form-item label="联系方式" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入电话号码" />
      </el-form-item>

      <el-form-item label="员工照片" prop="photoFile">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handlePhotoChange"
          :on-remove="handlePhotoRemove"
          accept="image/*"
        >
          <img v-if="photoUrl" :src="photoUrl" class="avatar" />
          <el-icon v-else><Plus /></el-icon>
          <div v-if="!photoUrl" class="el-upload__text">点击上传</div>
        </el-upload>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>

      <el-form-item label="所属部门" prop="departmentId">
        <el-select
          v-model="form.departmentId"
          placeholder="请选择部门"
          teleported
          style="width: 100%"
          popper-class="custom-select-dropdown"
        >
          <el-option
            v-for="dept in departmentList"
            :key="dept.departmentId"
            :label="dept.departmentName"
            :value="dept.departmentId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="岗位名称" prop="position">
        <el-input v-model="form.position" placeholder="请输入岗位名称" />
      </el-form-item>

      <el-form-item label="员工密码" prop="password">
        <el-input v-model="form.password" type="password" placeholder="请输入密码" />
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="form.confirmPassword"
          type="password"
          placeholder="请再次输入密码"
        />
      </el-form-item>

      <el-form-item label="员工状态" prop="status">
        <el-select
          v-model="form.status"
          placeholder="请选择状态"
          teleported
          style="width: 100%"
          popper-class="custom-select-dropdown"
        >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>

      <el-form-item label="身份证号码" prop="idCard">
        <el-input v-model="form.idCard" placeholder="请输入身份证号码" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped>
.add-emp-card {
  max-width: 700px;
  margin: 32px auto 0 auto;
  padding: 0;
  background: #fff;
  border-radius: 0;
  box-shadow: none;
}

.add-emp-card h2 {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 8px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-input,
.el-select,
.el-date-picker {
  width: 100%;
}

.el-button[type="primary"] {
  background: #2256c6;
  border: none;
  color: #fff;
  border-radius: 0;
  min-width: 120px;
  font-size: 1.1rem;
}

.el-button {
  border-radius: 0;
  min-width: 100px;
  font-size: 1.05rem;
}

.el-form-item:last-child {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.avatar-uploader {
  display: flex;
  align-items: center;
}

.avatar {
  width: 80px;
  height: 80px;
  display: block;
  border-radius: 4px;
  object-fit: cover;
  margin-right: 10px;
}
.date-format-note {
  margin-left: 8px;
  color: #999;
  font-style: italic;
  font-size: 0.9em;
  user-select: none;
}
</style>

<style>
.custom-select-dropdown {
  z-index: 9999 !important;
}
.el-picker-panel {
  z-index: 99999 !important;
}
</style>
